package com.gxc.string;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）。
 */
public class LevelOrder {

      public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

    public List<List<java.lang.Integer>> levelOrder(TreeNode root) {
          if (root == null) return new ArrayList<>();
          Queue<TreeNode> queue = new LinkedList<>();
          queue.add(root);

          List<List<java.lang.Integer>> res = new ArrayList<>();
          while (!queue.isEmpty()) {
              int size = queue.size();
              List<java.lang.Integer> list = new ArrayList<>();
              for (int i = 0; i < size; i++) {
                  TreeNode poll = queue.poll();
                  list.add(poll.val);
                  if (poll.left != null) queue.add(poll.left);
                  if (poll.right != null) queue.add(poll.right);
              }
              res.add(list);
          }
          return res;
    }

}
